package com.yy.micro.magic.data.service.trigger.impl;

import com.yy.micro.magic.data.domain.DynamicTriggerVo;
import com.yy.micro.magic.data.entity.DynamicTriggerEntity;
import com.yy.micro.magic.data.repository.DynamicTriggerRepository;
import com.yy.micro.magic.data.service.trigger.MagicTriggerService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class MagicTriggerServiceImpl implements MagicTriggerService {
    @Autowired
    private DynamicTriggerRepository repository;
    @Override
    public DynamicTriggerVo find(final String planCode, final String trigger) {
        DynamicTriggerEntity entity =repository.findByPlanCodeAndTriggerAndDisable(planCode,trigger,false);
        if (null == entity){
            return null;
        }
        return DynamicTriggerVo.create().from(entity);
    }

    @Override
    public List<DynamicTriggerVo> find(final String planCode) {
        List<DynamicTriggerEntity> list = repository.findByPlanCodeAndDisable(planCode,false);
        if (!CollectionUtils.isEmpty(list)){
            return list.stream().map(t-> DynamicTriggerVo.create().from(t)).collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public DynamicTriggerVo apply(final DynamicTriggerVo request) {
        DynamicTriggerEntity entity = request.to();
        DynamicTriggerEntity e=repository.save(entity);
        return DynamicTriggerVo.create().from(e);
    }

    @Override
    public DynamicTriggerVo load(final Long id) {
        Optional<DynamicTriggerEntity> entity =repository.findById(id);
        if (entity.isPresent()){
            return DynamicTriggerVo.create().from(entity.get());
        }
        return null;
    }
}
